package heap;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

public class TopK {

    public static void main(String[] args) {
        int[] nums = {1,1,1,2,2,3};
        int k = 2;
    }

    public int[] topK(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>((int)(nums.length / 0.75));
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        PriorityQueue<Map.Entry<Integer, Integer>> maxHeap =
                new PriorityQueue<>((a,b)->b.getValue() - a.getValue());
        for (Map.Entry<Integer, Integer> entry : map.entrySet()){
            maxHeap.offer(entry);
        }

        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = maxHeap.poll().getKey();
        }
        return res;
    }

}
